/**
 * 
 */
package info.niwota.web.apache;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;

/**
 * @author qiangli
 *
 */
public class ResourceUtils {

	private static long seq = System.currentTimeMillis();

	private static final int BUFSIZE = 1024;

	private static String tmpprefix = ResourceUtils.class
			.getSimpleName();

	public static void closeSilently(Closeable c) {
		if (c == null) {
			return;
		}
		try {
			c.close();
		} catch (Throwable t) {
			// do nothing
		}
	}

	public static File createTempFile(File cacheDir) throws IOException {
		File f = new File(cacheDir, nextTempName());
		f.deleteOnExit();
		return f;
	}


	synchronized private static String nextTempName() {
		seq++;
		return tmpprefix + seq + ".tmp";
	}

	/**
	 * Save resource under assets/ to a file
	 * 
	 * @param name
	 *            relative path in assets e.g image/bg.png
	 * @param file
	 * @throws IOException
	 */
	public static void copyAsset(Context ctx, String name, File file) throws Exception {
		AssetManager am = ctx.getAssets();
		InputStream is = null;
		OutputStream os = null;
		try {
			is = am.open(name);
			os = new FileOutputStream(file);
			copy(is, os);
		} catch (Exception e) {
			file.delete();
			throw e;
		} finally {
			closeSilently(is);
			closeSilently(os);
		}
	}

	/**
	 * Save resource under res/ to a file
	 * 
	 * @param resid
	 *            int generated in R.java
	 * @param file
	 * @throws IOException
	 */
	public static void copyRes(Context ctx, int resid, File file) throws Exception {
		InputStream is = null;
		OutputStream os = null;
		try {
			is = ctx.getResources().openRawResource(resid);
			os = new FileOutputStream(file);
			copy(is, os);
			
			file.setLastModified(System.currentTimeMillis());
		} catch (Exception e) {
			file.delete();
			throw e;
		} finally {
			closeSilently(is);
			closeSilently(os);
		}
	}

	public static boolean save(Drawable image, OutputStream fos) throws IOException {
		final CompressFormat cf = CompressFormat.JPEG;
		final int alpha = 100;
		Bitmap bitmap = null;
		if (image instanceof BitmapDrawable) {
			bitmap = ((BitmapDrawable) image).getBitmap();
		} else {
			final Config bc = Bitmap.Config.ARGB_8888;
			final int w = image.getIntrinsicWidth();
			final int h = image.getIntrinsicHeight();
			bitmap = Bitmap.createBitmap(w, h, bc);
			Canvas c = new Canvas(bitmap);
			c.drawColor(Color.WHITE);
			image.setBounds(0, 0, w, h);
			image.setAlpha(alpha);
			image.setDither(true);
			image.draw(c);
		}
		//
		final int q = 100;
		return bitmap.compress(cf, q, fos);
	}

	/**
	 * Save resource in the package to a file
	 * 
	 * @param resName
	 *            dots replaced with slash e.g.
	 *            /info/niwota/webapp/Constants.class
	 * @param file
	 * @throws Exception 
	 * @return false if resource not found
	 */
	public static boolean copyClassResource(String resName, File file) throws Exception
			 {
		InputStream is = null;
		OutputStream os = null;
		try {
			is = ResourceUtils.class.getResourceAsStream(resName);
			if (is == null) {
				return false;
			}
			os = new FileOutputStream(file);
			copy(is, os);
		} catch (Exception e) {
			file.delete();
			throw e;
		} finally {
			closeSilently(is);
			closeSilently(os);
		}
		return true;
	}

	public static void copyText(InputStream is, Appendable out) throws IOException {
		BufferedReader r = new BufferedReader(new InputStreamReader(is), BUFSIZE);
		while (true) {
			String l = r.readLine();
			if (l == null) {
				break;
			}
			out.append(l);
			out.append("\r\n");
		}
	}

	public static void copy(InputStream is, OutputStream os) throws IOException {
		byte[] buf = new byte[BUFSIZE];
		while (true) {
			int read = is.read(buf);
			if (read == -1) {
				break;
			}
			if (read > 0) {
				os.write(buf, 0, read);
			}
		}
		os.flush();
	}
	
	public static String scan(String cookies, String key) {
		if (TextUtils.isEmpty(cookies)) {
			return null;
		}
		final String[] sa = cookies.split(";");
		final String key_ = key + "=";
		for (int i = 0; i < sa.length; i++) {
			String sai = sa[i].trim();
			if (sai.startsWith(key_)) {
				return sai.substring(key.length() + 1);
			}
		}
		return null;
	}
}
